package utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;

import config.DbManager;

public class BadWords {
	private static File wordsFile = new File(BadWords.class.getResource("/").getPath()+"badWords.txt");
	private static List<String> words = new ArrayList<String>();

	/**
	 * 从文件读取获取敏感字数组
	 * @throws IOException 
	 * */
	public static synchronized void loadWords()  {
		LineIterator lines;
		try {
			lines = FileUtils.lineIterator(wordsFile, "utf-8");
			// 循环赋值
			while (lines.hasNext()) {
				String line = lines.nextLine();
				if (StringUtils.isNotBlank(line))
					words.add(StringUtils.trim(line).toLowerCase());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 处理字符串，将敏感字用*代替
	 * */
	public static String filterBadWords(String content) {
		if(words.size() == 0){
			loadWords();
		}
		for (String word : words) {
			if (content != null && content.indexOf(word) >= 0) {
				content = content.replaceAll(word, "*");
			}
		}
		return content;
	}
}
